import Module from '../Module';
import $ from 'jquery';


export default class Button extends Module {
    getEditor() {
        if (!this.editor) this.editor = this.opts.editor;
        return this.editor;
    }
    _init() {
        this.editor = this.getEditor();
        this.title = this._t(this.name);
        let k, len, ref, tag;
        this.render();
        this.el.on('mousedown', (e) => {
            e.preventDefault();
            e.stopPropagation();
            let exceed, noFocus, param;
            noFocus = this.needFocus && !this.editor.inputManager.focused;
            if (this.el.hasClass('disabled') || noFocus) return false;
            if (this.menu) {
                this.wrapper.toggleClass('menu-on').siblings('li').removeClass('menu-on');
                if (this.wrapper.is('.menu-on')) {
                    exceed = this.menuWrapper.offset().left + this.menuWrapper.outerWidth() + 5 - this.editor.wrapper.offset().left - this.editor.wrapper.outerWidth();
                    if (exceed > 0) this.menuWrapper.css({ 'left': 'auto', 'right': 0 });
                    this.trigger('menuexpand');
                }
            } else {
                param = this.el.data('param');
                this.command(param);
            }
        });
        this.wrapper.on('click', 'a.menu-item', e => {
            let btn, noFocus, param;
            e.preventDefault();
            e.stopPropagation();
            btn = $(e.currentTarget);
            this.wrapper.removeClass('menu-on');
            noFocus = this.needFocus && !this.editor.inputManager.focused;
            if (btn.hasClass('disabled') || noFocus) return;

            this.editor.toolbar.wrapper.removeClass('menu-on');
            param = btn.data('param');
            this.command(param);
        });
        this.wrapper.on('mousedown', 'a.menu-item', e => false);
        this.editor.on('blur', () => {
            let editorActive;
            editorActive = this.editor.body.is(':visible') && this.editor.body.is('[contenteditable]');
            if (!(editorActive && !this.editor.clipboard.pasting)) return;
            this.setActive(false);
            return this.setDisabled(false);
        });
        if (this.shortcut != null) {
            this.editor.hotkeys.add(this.shortcut, e => {
                this.el.mousedown();
                return false;
            });
        }
        ref = this.htmlTag.split(',');
        for (k = 0, len = ref.length; k < len; k++) {
            tag = ref[k];
            tag = $.trim(tag);
            if (tag && $.inArray(tag, this.editor.formatter._allowedTags) < 0) this.editor.formatter._allowedTags.push(tag);
        }
        return this.editor.on('selectionchanged', e => {
            if (this.editor.inputManager.focused) return this._status();
        });
    }
    iconClassOf(icon) {
        return icon ? `simditor-icon simditor-icon-${icon}` : '';
    }
    setIcon(icon) {
        return this.el.find('span').removeClass().addClass(this.iconClassOf(icon)).text(this.text);
    }
    render() {
        this.wrapper = $(this._tpl.item).appendTo(this.editor.toolbar.list);
        this.el = this.wrapper.find('a.toolbar-item');
        this.el.attr('title', this.title).addClass(`toolbar-item-${this.name}`).data('button', this);
        this.setIcon(this.icon);
        if (!this.menu) {
            return;
        }
        this.menuWrapper = $(this._tpl.menuWrapper).appendTo(this.wrapper);
        this.menuWrapper.addClass(`toolbar-menu-${this.name}`);
        return this.renderMenu();
    }
    renderMenu() {
        let $menuBtnEl, $menuItemEl, k, len, menuItem, ref, ref1, results;
        if (!Array.isArray(this.menu)) return;
        this.menuEl = $('<ul/>').appendTo(this.menuWrapper);
        ref = this.menu;
        results = [];
        for (k = 0, len = ref.length; k < len; k++) {
            menuItem = ref[k];
            if (menuItem === '|') {
                $(this._tpl.separator).appendTo(this.menuEl);
                continue;
            }
            $menuItemEl = $(this._tpl.menuItem).appendTo(this.menuEl);
            $menuBtnEl = $menuItemEl.find('a.menu-item').attr({
                'title': (ref1 = menuItem.title) != null ? ref1 : menuItem.text,
                'data-param': menuItem.param
            }).addClass(`menu-item-${menuItem.name}`);
            if (menuItem.icon) {
                results.push($menuBtnEl.find('span').addClass(this.iconClassOf(menuItem.icon)));
            } else {
                results.push($menuBtnEl.find('span').text(menuItem.text));
            }
        }
        return results;
    }
    setActive(active) {
        if (active === this.active) {
            return;
        }
        this.active = active;
        return this.el.toggleClass('active', this.active);
    }
    setDisabled(disabled) {
        if (disabled === this.disabled) {
            return;
        }
        this.disabled = disabled;
        return this.el.toggleClass('disabled', this.disabled);
    }
    _disableStatus() {
        let disabled;
        let endNodes;
        let startNodes;
        startNodes = this.editor.selection.startNodes();
        endNodes = this.editor.selection.endNodes();
        disabled = startNodes.filter(this.disableTag).length > 0 || endNodes.filter(this.disableTag).length > 0;
        this.setDisabled(disabled);
        if (this.disabled) {
            this.setActive(false);
        }
        return this.disabled;
    }
    _activeStatus() {
        let active;
        let endNode;
        let endNodes;
        let startNode;
        let startNodes;
        startNodes = this.editor.selection.startNodes();
        endNodes = this.editor.selection.endNodes();
        startNode = startNodes.filter(this.htmlTag);
        endNode = endNodes.filter(this.htmlTag);
        active = startNode.length > 0 && endNode.length > 0 && startNode.is(endNode);
        this.node = active ? startNode : null;
        this.setActive(active);
        return this.active;
    }
    _status() {
        this._disableStatus();
        if (this.disabled) {
            return;
        }
        return this._activeStatus();
    }
    command() { }
    _t(...args) {
        return super._t(...args) || this.getEditor()._t(...args);
    }
}
Button.prototype._tpl = {
    item: '<li><a tabindex="-1" unselectable="on" class="toolbar-item" href="javascript:;"><span></span></a></li>',
    menuWrapper: '<div class="toolbar-menu"></div>',
    menuItem: '<li><a tabindex="-1" unselectable="on" class="menu-item" href="javascript:;"><span></span></a></li>',
    separator: '<li><span class="separator"></span></li>'
};
Button.prototype.name = '';
Button.prototype.icon = '';
Button.prototype.title = '';
Button.prototype.text = '';
Button.prototype.htmlTag = '';
Button.prototype.disableTag = '';
Button.prototype.menu = false;
Button.prototype.active = false;
Button.prototype.disabled = false;
Button.prototype.needFocus = true;
Button.prototype.shortcut = null;